package dao

import (
	"context"
	"pay/api/pay"
	"pay/internal/model"
)

func (d *Dao) FindValidPayOrdersByBizNo(ctx context.Context, bizType pay.BizType, bizNo string) (
	orders []*model.Order, err error) {
	err = d.processSqlError(d.TransContext(ctx).Model(&model.Order{}).Where(
		"biz_type = ? AND biz_no = ? AND status not in ?",
		uint8(bizType), bizNo, []int{
			int(pay.PayOrderStatus_PAY_ORDER_STATUS_CLOSED),
			int(pay.PayOrderStatus_PAY_ORDER_STATUS_FAILED),
		}).Scan(&orders).Error)
	return
}

func (d *Dao) DeleteSchedule(ctx context.Context, scheduleType uint8, orderId uint64) (err error) {
	if err = d.TransContext(ctx).Delete(&model.Schedule{},
		"schedule_type = ? and order_id = ?",
		scheduleType, orderId).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	return
}

func (d *Dao) GetOrderByOrderNumber(ctx context.Context, orderNumber string) (
	order *model.Order, err error) {
	order = &model.Order{}
	err = d.processSqlError(d.TransContext(ctx).Model(&model.Order{}).Where(
		"order_number = ?", orderNumber).Take(order).Error)
	return
}

func (d *Dao) GetRefundByOrderNumber(ctx context.Context, orderNumber string) (
	order *model.Refund, err error) {
	order = &model.Refund{}
	err = d.processSqlError(d.TransContext(ctx).Model(&model.Refund{}).Where(
		"order_number = ?", orderNumber).Take(order).Error)
	return
}

func (d *Dao) GetOrderByOrderId(ctx context.Context, orderId uint64) (
	order *model.Order, err error) {
	order = &model.Order{}
	err = d.processSqlError(d.TransContext(ctx).Model(&model.Order{}).Where(
		"id = ?", orderId).Take(order).Error)
	return
}

func (d *Dao) FindRefundsByPayOrderId(ctx context.Context, parentId uint64) (
	refunds []*model.Refund, err error) {
	err = d.processSqlError(d.TransContext(ctx).Model(&model.Refund{}).Where(
		"parent_id = ?", parentId).Scan(&refunds).Error)
	return
}
